//
//  ZYOAuthViewController.swift
//  CZ29WeiboZYH
//
//  Created by 沐颜澈 on 16/6/26.
//  Copyright © 2016年 muyanche. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking



class ZYOAuthViewController: UIViewController {
    
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
    }
    
    
    
    @objc private func cancleClick() {
        
        dismissViewControllerAnimated(true, completion: nil)
    
    }
    
     //626-------------------------------------------------------------------
     //自动填充的按钮监听事件
    @objc private func autoFillClick() {
        
        print("按钮点击了")
        let jsString = "document.getElementById('userId').value='muyanchedetiankong@163.com',document.getElementById('passwd').value='2014wykl591314'"
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    
    }
    
    //-------------------------------------------------------------------

    
    //MARK - 设置导航栏
    func setNavc() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancleClick")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFillClick")
        
        navigationController?.title = "OAUTH登录"
    }
    
    
    //MARK - 设置视图
    private func setupUI() {
        view.backgroundColor = UIColor.whiteColor()
        
        setNavc()
    }
    
    //626懒加载控件
    private lazy var webView: UIWebView = {
        //626.2-------------------------------------------------------------------
        
        let view = UIWebView()
        
        view.delegate = self
        
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(REDIRECT_URI)")!
        
        let request = NSURLRequest(URL: url)
        view.loadRequest(request)
        return view
    
    }()
    
}

//626.2-------------------------------------------------------------------
//代理方法

extension ZYOAuthViewController:UIWebViewDelegate {
    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        //调用.show的方法
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        //调用取消控制器的方法
        SVProgressHUD.dismiss()
    }
    
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("加载失败")
    }
    
    //当webView加载request的时候,返回true表示继续加载,返回false表示加载失败
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL?.absoluteString)
        
        //判断url是否有值,url的前缀就是我们的回调值
        let urlString = request.URL?.absoluteString
        if let u = urlString where u.hasPrefix(REDIRECT_URI) {
            //请求参数的键值对
            let query = request.URL?.query
            
            //可选值的判断,截取字符串
            if let z = query {
                
                //截取字符串
                let code = z.substringFromIndex("code=".endIndex)
                print("继续坚持不放弃: \(code)")
                
                
                //调用loadUserAccount的方法
                loadUserAccount(code)
            
            }
        
        }
        
        
        return true
        
    }
    
}


extension ZYOAuthViewController {
    func loadUserAccount(code: String) {
        /*
        client_id 	true 	string 	申请应用时分配的AppKey。
        client_secret 	true 	string 	申请应用时分配的AppSecret。
        grant_type 	true 	string 	请求的类型，填写authorization_code
        
        
        grant_type为authorization_code时
        
        必选 	类型及范围 	说明
        code 	true 	string 	调用authorize获得的code值。
        redirect_uri 	true 	string 	回调地址，需需与注册应用里的回调地址一致。
        
        */
        
        
        ZYNetworkTools.sharedNetworkTools.oauthLoadUserAccount(code, success: { (response) -> () in
            
           // print("请求成功\(response)")
            
            //进行判断,看请求的数据resp是否有值,是否能转换成数据
            
            guard let resp = response as? [String: AnyObject] else {
                print("返回的数据不是一个字典")
                return
            }
            
            //传入一个字典
            let userAccount = ZYUserAccountModel(dict: resp)
            
            //print(userAccount) //调用------
            self.loadUserInfo(userAccount)
            
            }) { (error) -> () in
                
                print("请求失败\(error)")
                SVProgressHUD.showErrorWithStatus("请求失败")
                
        }
        
        
    }
    
    //用户个人信息
    func loadUserInfo(userAccount:ZYUserAccountModel) {
    
        ZYNetworkTools.sharedNetworkTools.oauthLoadUserInfo(userAccount, success: { (response) -> () in
            
            //判断是否有值是否可以转化成字典
            guard let resp = response as? [String: AnyObject] else {
                return
            
            }
            
            //前三个是通过字典转模型,后面三个是手动赋值
            userAccount.avatar_large = resp["avatar_large"] as? String
            userAccount.screen_name = resp["screen_name"] as? String
            
            
            //626==========
            //通过归档来保存数据
            ZYUserAccountTools.sharedTools.saveUserAccount(userAccount)
            
            print(userAccount)
            
            let result = ZYUserAccountTools.sharedTools.userAccount
            
            print(result)
            
            }) { (error) -> () in
                
                print(error)
        }
    
    }

}





extension ZYOAuthViewController {
    func demo() {
    
        //请求url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求的参数
        let params = [
            "client_id":APPKEY,
            "client_secret":APPSECRET,
            "grant_type":"authorization_code",
            "code": "",
            "redirect_uri":REDIRECT_URI
            
        ]
        print(params)
        
        let manager = AFHTTPSessionManager()
        
        //请求的格式
        manager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        
        manager.POST(urlString, parameters: params, progress: nil, success: { (_, response) -> Void in
            
            print("请求成功:\(response)")
            
            
            }) { (_, error) -> Void in
                
                print("请求失败:\(error)")
                
                SVProgressHUD.showErrorWithStatus("请求失败~")
                
        }

    }

}



